﻿// owner 蒋家伟

#include "TaskTransfer.h"

// qt
#include <QThread>

// jsdk
#include "TaskTransferWorker.h"
#include "Dbg_Warn_Define.h"
#include "TaskId.h"

using namespace jsdk;

jsdk::TaskTransfer::TaskTransfer()
{
    m_opTaskTransferWorker.swap(TaskTransferWorker::create());
    DBG_WARN_AND_RETURN_VOID_UNLESS(m_opTaskTransferWorker, L"任务分发器为初始化失败", L"蒋家伟", L"2023-07-31");
    m_opThread.swap(NEW_AS_OWNERPTR_WITH_DELETER(QThread, ThreadDeleter));
    DBG_WARN_AND_RETURN_VOID_UNLESS(m_opThread, L"任务分发器线程对象初始化失败", L"蒋家伟", L"2023-07-31");
    bool success = connect(this, SIGNAL(taskReadyRead(QVariant)), m_opTaskTransferWorker.get(), SLOT(onTaskReadyRead(QVariant)));
    DBG_WARN_AND_RETURN_VOID_UNLESS(success, L"任务分发器线程信号与槽连接失败", L"蒋家伟", L"2023-07-31");
    success = connect(this, SIGNAL(taskReadyRead()), m_opTaskTransferWorker.get(), SLOT(onTaskReadyRead()));
    DBG_WARN_AND_RETURN_VOID_UNLESS(success, L"任务分发器线程信号与槽连接失败", L"蒋家伟", L"2023-07-31");
    m_opTaskTransferWorker->moveToThread(m_opThread.get());
    m_opThread->start();
}

jsdk::TaskTransfer* jsdk::TaskTransfer::get()
{
    static TaskTransfer s_TaskTransfer;
    return &s_TaskTransfer;
}

jsdk::TaskTransfer::~TaskTransfer()
{
}

void jsdk::TaskTransfer::taskReady() const
{
    emit taskReadyRead();
}

void jsdk::TaskTransfer::taskReady(const TaskId& taskId) const
{
    DBG_WARN_AND_RETURN_VOID_UNLESS(m_opTaskTransferWorker && m_opThread, L"任务分发线程与工作对象应该同时存在", L"蒋家伟", L"2023-07-31");
    QVariant data;
    data.setValue(taskId);
    emit taskReadyRead(data);
}